package com.apes.framework.config.druid.stat;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import com.alibaba.druid.stat.JdbcSqlStat;
import com.apes.framework.api.SpringManager;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.Tools;
import com.apes.framework.util.monitor.druid.sql.SqlStack;
import com.apes.framework.util.monitor.druid.sql.SqlStackService;

import java.util.ArrayList;
import java.util.List;

public class ApesStatFilter extends StatFilter {
    private List<SqlStack> sqlStacks = new ArrayList<>();

    public JdbcSqlStat createSqlStat(StatementProxy statement, String sql) {
        JdbcSqlStat sqlStat = super.createSqlStat(statement, sql);
        if (isEnable()) {
            long sqlHash = sqlStat.getSqlHash();
            String id = MD5Util.encrypt(Tools.formatStackTrace("com.apes.") + "|" + sqlHash);
            SqlStack sqlStack = new SqlStack();
            sqlStack.setId(id);
            sqlStack.setSql(sql);
            sqlStack.setSqlHash(String.valueOf(sqlHash));
            sqlStack.setStackTrace(Tools.formatStackTrace());
            if (getStackService() == null) {
                sqlStacks.add(sqlStack);
            } else {
                if (!sqlStacks.isEmpty()) {
                    for (SqlStack stack : sqlStacks) {
                        saveSqlStack(stack);
                    }
                    sqlStacks.clear();
                }
                saveSqlStack(sqlStack);
            }
        }
        return sqlStat;
    }

    private boolean isEnable() {
        if (getStackService() == null) {
            return true;
        }
        return getStackService().isEnable();
    }

    private void saveSqlStack(SqlStack stack) {
        getStackService().add(stack);
    }


    private SqlStackService stackService;

    public SqlStackService getStackService() {
        if (SpringManager.getApplicationContext() == null) {
            return null;
        }
        if (stackService == null) {
            stackService = SpringManager.getBean(SqlStackService.class);
        }
        return stackService;
    }

}
